package com.cr.common.config;

import lombok.Data;
import okhttp3.*;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "caridentification")
public class CarIdentificationConfig {
    private String apiKey;
    private String secretKey;
    private String url;

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     *   通过用户的AK，SK生成鉴权签名
     */
    public String getAccessToken(){
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + getApiKey()
                + "&client_secret=" + getSecretKey());

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            return new JSONObject(response.body().string()).getString("access_token");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}